package io.kiki.stack.http.feign.form.spring.converter;

import lombok.NonNull;
import lombok.Value;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * Straight-forward implementation of interface {@link MultipartFile} where the file data is held as
 * a byte array in memory.
 */
@Value
class ByteArrayMultipartFile implements MultipartFile {

    String name;

    String originalFilename;

    String contentType;

    @NonNull
    byte[] bytes;

    @Override
    public boolean isEmpty() {
        return bytes.length == 0;
    }

    @Override
    public long getSize() {
        return bytes.length;
    }

    @Override
    public InputStream getInputStream() {
        return new ByteArrayInputStream(bytes);
    }

    @Override
    public void transferTo(File destination) throws IOException {
        try (var outputStream = new FileOutputStream(destination)) {
            outputStream.write(bytes);
        }
    }
}
